import datetime
from typing import Optional

from sqlalchemy import ForeignKey, String, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.application.proxy.enums import AuthorizationType, ProxyStatus, ReloadType
from src.infrastructure.db.models.base import Base
from src.infrastructure.db.models.m2ms import orders_proxies, proxies_users


class Proxy(Base):
    __tablename__ = "proxy"
    __mapper_args__ = {"eager_defaults": True}

    id: Mapped[int] = mapped_column(primary_key=True)
    port_https: Mapped[int] = mapped_column(nullable=False, unique=False)
    login: Mapped[str] = mapped_column(String(50), nullable=False, unique=True)
    password: Mapped[str] = mapped_column(String(50), nullable=False, unique=True)
    server_id: Mapped[int] = mapped_column(ForeignKey("server.id"))
    server = relationship("Server", back_populates="proxies")
    orders = relationship("Order", secondary=orders_proxies, back_populates="proxies")
    users = relationship("User", secondary=proxies_users, back_populates="proxies")
    user_id: Mapped[int] = mapped_column(ForeignKey("user.id"))  # TODO Возможно удалить
    status: Mapped[ProxyStatus] = mapped_column(server_default="available")
    authorization_type: Mapped[AuthorizationType] = mapped_column(server_default="by_password")
    reload_type: Mapped[ReloadType]
    reload_period: Mapped[int] = mapped_column(server_default="0")
    reload_link: Mapped[Optional[str]] = mapped_column(String(50))
    was_added: Mapped[datetime.datetime] = mapped_column(server_default=func.now())

    def __repr__(self):
        return f"<Proxy №{self.id} {self.port_https}>"

    def __str__(self):
        return self.__repr__()
